<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百度千帆 SSE 流式输出</title>
</head>
<body>
    <h2>百度千帆 SSE 流式响应</h2>
    <button onclick="startRequest()">开始请求</button>
    <button onclick="stopRequest()">停止请求</button>
    <pre id="output"></pre>

    <script>
        let eventSource = null;

        function startRequest() {
            // 防止重复连接
            if (eventSource) {
                eventSource.close();
            }

            // 清空之前的内容
            document.getElementById("output").textContent = "";

            eventSource = new EventSource("http://localhost:3000/sse");

            eventSource.onmessage = function(event) {
                if (event.data === "[DONE]") {
                    eventSource.close(); // 关闭 SSE 连接
                } else {
                    document.getElementById("output").textContent += event.data + "\n";
                }
            };

            eventSource.onerror = function() {
                console.error("SSE 连接错误！");
                eventSource.close();
            };
        }

        function stopRequest() {
            if (eventSource) {
                eventSource.close();
                console.log("SSE 连接已关闭");
            }
        }
    </script>
</body>
</html>
